package com.bytz.modules.cms.order.schedule;

import cn.hutool.core.bean.BeanUtil;
import com.bytz.common.system.vo.LoginUser;
import com.bytz.common.util.SecurityUtils;
import com.bytz.modules.cms.order.entity.Order;
import com.bytz.modules.cms.order.event.GeSalesQuoteEvent;
import com.bytz.modules.cms.order.service.IAdminOrderService;
import com.bytz.modules.system.service.ISysUserService;
import com.bytz.modules.system.vo.SysUserVo;
import lombok.extern.slf4j.Slf4j;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Component;

import java.util.List;

@Slf4j
@Component
@DisallowConcurrentExecution
public class GenerateSalesQuoteJob implements Job {

    @Autowired
    private IAdminOrderService orderService;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private ApplicationEventPublisher publisher;

    @Override
    public void execute(JobExecutionContext jobExecutionContext) {
        log.info("开始执行报价单定时任务==================");
        // 自动登陆
        SysUserVo syscall = sysUserService.getUserByName("syscall");
        SecurityUtils.setLoginUser(BeanUtil.copyProperties(syscall, LoginUser.class));
        // 获取相关订单
        List<Order> orders = orderService.getSalesQuoteOrders();
        // 需要自动创建 报价单 的订单自动创建
        orders.forEach(order -> publisher.publishEvent(new GeSalesQuoteEvent(order)));
        SecurityUtils.setLoginUser(null);
        log.info("报价单定时任务执行完毕==================");
    }
}
